package com.jhgsys.internal.sypq.controller;


import com.jhgsys.internal.common.annotation.Log;
import com.jhgsys.internal.common.constant.FileUploadConstant;
import com.jhgsys.internal.common.controller.BaseController;
import com.jhgsys.internal.common.controller.FileUploader;
import com.jhgsys.internal.common.entity.*;
import com.jhgsys.internal.common.exception.FebsException;
import com.jhgsys.internal.common.utils.*;
import com.jhgsys.internal.sypq.entity.*;
import com.jhgsys.internal.sypq.service.*;
import com.jhgsys.internal.system.entity.User;
import io.swagger.v3.core.util.Json;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.util.*;


/**
 * 任务管理 Controller
 *
 * @author ganjun
 * @date 2024-11-18 10:06:38
 */
@Slf4j
@Validated
@Controller
public class TaskController extends BaseController {

    @Autowired
    private ITaskService taskService;
    @Autowired
    private ISypqProjectService projectService;
    @Autowired
    private IResourceService resourceService;


    @GetMapping(FebsConstant.VIEW_PREFIX + "task")
    @RequiresPermissions("task:view")
    public ModelAndView taskIndex(@RequestParam(name="projectName", required=false, defaultValue="") String projectName) {
        String viewPath = jumpPage("sypq/task/taskList");
        ModelAndView modelAndView = new ModelAndView(viewPath);
        modelAndView.addObject("projectName", projectName);
        boolean isAdmin = isAdmin();
        User user = (User) getSubject().getPrincipal();
        modelAndView.addObject("userid", user.getUserId());
        modelAndView.addObject("isAdmin", isAdmin);
        return modelAndView;
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "task/add")
    @RequiresPermissions("task:add")
    public String taskAdd(Model model) {
        Task task = new Task();
        String taskcode = taskService.getNewTaskcode();
        task.setTaskCode(taskcode);
        model.addAttribute("task", task);
        String userid=getCurrentUser().getUserId();
        if(isAdmin()){
            userid="";
        }
        model.addAttribute("projectList", projectService.findSypqProjectList(new SypqProjectDto(),userid));
        model.addAttribute("resourceList", resourceService.findResourceList(new Resource()));
        return jumpPage("sypq/task/taskEdit");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "task/update/{id}")
    @RequiresPermissions("task:edit")
    public String taskUpdate(Model model, @PathVariable("id") String id) {
        TaskDto taskDto = new TaskDto();
        taskDto.setTaskCode(id);
        List<TaskDto> list = taskService.findTaskList(taskDto);
        TaskDto task = new TaskDto();
        if (list.size() > 0) {
            task = list.get(0);
        }
        model.addAttribute("task", task);
        String userid=getCurrentUser().getUserId();
        if(isAdmin()){
            userid="";
        }
        model.addAttribute("projectList", projectService.findSypqProjectList(new SypqProjectDto(),userid));
        model.addAttribute("resourceList", resourceService.findResourceList(new Resource()));
        return jumpPage("sypq/task/taskEdit");
    }

    /**
     * 查询（所有）
     * @author ganjun
     * @date 2024-11-18 10:06:38
     */
    @GetMapping("task")
    @ResponseBody
    @RequiresPermissions("task:view")
    public FebsResponse getAllTasks(Task task) {
        try {
            return success(taskService.findTaskList(task));
        } catch (Exception ex) {
            return failure(ex);
        }

    }

    /**
     * 查询（分页）
     * @author ganjun
     * @date 2024-11-18 10:06:38
     */
    @GetMapping("task/list")
    @ResponseBody
    @RequiresPermissions("task:view")
    public FebsResponse taskList(QueryRequest request, TaskDto taskDto) {
        try {
            String userid=getCurrentUser().getUserId();
            Boolean isAdmin=isAdmin();
            if(isAdmin){
                userid="";
            }
            Map<String, Object> dataTable = getDataTable(this.taskService.findTaskPage(request, taskDto,userid));
            return success(dataTable);
        } catch (Exception ex) {
            return failure(ex);
        }
    }


    @GetMapping("task/getModelList")
    @ResponseBody
    public FebsResponse getModelList(@RequestParam("projectCode") String projectCode,
               @RequestParam("taskCode")String taskCode) {
        return new FebsResponse().success().data(taskService.getModelListByProjectcode(projectCode,taskCode));
    }

    /**
     * 新增 Task
     * @author ganjun
     * @date 2024-11-18 10:06:38
     */
    @Log("新增Task")
    @PostMapping("task")
    @ResponseBody
    @RequiresPermissions("task:add")
    public FebsResponse addTask(@RequestBody TaskDto taskDto) throws FebsException {
        try {
            this.taskService.createTask(taskDto);
            return success();
        } catch (Exception ex) {
            return failure(ex, "新增失败");
        }
    }

    @RequestMapping(value = "task/upload", method = RequestMethod.POST)
    @ResponseBody
    public FebsResponse uploadImage(Plupload plupload, HttpServletRequest request) {
        if (!FileUploader.checkFileType(plupload.getName(), FileUploader.allowImageFiles)
            && !FileUploader.checkFileType(plupload.getName(), FileUploader.allowVideoFiles)
            && !FileUploader.checkFileType(plupload.getName(), FileUploader.allowOtherFiles)) {
            return new FebsResponse().fail().message(FileUploader.MSG_ERROR_FILE_TYPE);
        }
        plupload.setFilePath(FileUploadConstant.BASE_FILE_PATH);
        FebsResponse objects = FileUploader.fileUpCommon(plupload, request, plupload.getFilePath());
        return objects;
    }


    /**
     * 逻辑删除 Task
     * @author ganjun
     * @date 2024-11-18 10:06:38
     */
    @Log("逻辑删除Task")
    @GetMapping("task/delete/{id}")
    @ResponseBody
    @RequiresPermissions("task:delete")
    public FebsResponse deleteTask(@PathVariable("id") String taskIds) throws FebsException {
        try {
            Task task = new Task();
            task.setDeletedBy(getCurrentUser().getUserName());
            task.setDeletedTime(new Date());
            task.setDeletedFlg(FebsConstant.INVALID);
            this.taskService.deleteTask(task, taskIds);
            return success();
        } catch (Exception ex) {
            return failure(ex, "删除失败");
        }
    }

    /**
     * 物理删除 Task
     * @author ganjun
     * @date 2024-11-18 10:06:38
     */
    @Log("物理删除Task")
    @GetMapping("task/physicallyDelete/{id}")
    @ResponseBody
    @RequiresPermissions("task:delete")
    public FebsResponse physicallyDeleteTask(@PathVariable("id") String taskIds) throws FebsException {
        try {
            this.taskService.physicallyDeleteTask(taskIds);
            return success();
        } catch (Exception ex) {
            return failure(ex, "删除失败");
        }
    }

    /**
     * 修改 Task
     * @author ganjun
     * @date 2024-11-18 10:06:38
     */
    @Log("修改Task")
    @PostMapping("task/update")
    @ResponseBody
    @RequiresPermissions("task:edit")
    public FebsResponse updateTask(@RequestBody TaskDto taskDto) throws FebsException {
        try {
            this.taskService.updateTask(taskDto);
            return success();
        } catch (Exception ex) {
            return failure(ex, "修改失败");
        }
    }


    @GetMapping(FebsConstant.VIEW_PREFIX + "task/detail/{id}")
    @RequiresPermissions("task:detail")
    public String sypqProjectDetail(Model model, @PathVariable("id") String id,@RequestParam("type") String type) {
        TaskDto taskDto = new TaskDto();
        taskDto.setTaskCode(id);
        List<TaskDto> list = taskService.findTaskList(taskDto);
        TaskDto task = new TaskDto();
        if (list.size() > 0) {
            task = list.get(0);
        }
        model.addAttribute("task", task);
        model.addAttribute("type", type);
        model.addAttribute("projectList", projectService.findSypqProjectList(new SypqProjectDto(),""));
        model.addAttribute("resourceList", resourceService.findResourceList(new Resource()));
        return jumpPage("sypq/task/taskDetail");
    }

    @Log("检查项目名称或编码是否存在")
    @GetMapping("task/check")
    @ResponseBody
    public FebsResponse   checkTask(Task task) throws FebsException {
        String   result=   this.taskService.checkTask(task);
        return   new FebsResponse().success().data(result);
    }

    @Log("任务完成")
    @PostMapping("task/nonScheduleComplete")
    @ResponseBody
    @RequiresPermissions("progress:complete")
    public FebsResponse completeNonScheduleTask(@RequestBody TaskDto taskDto) throws FebsException {
        try {
            this.taskService.completeNonScheduleTask(taskDto);
            return success();
        } catch (Exception ex) {
            return failure(ex, "修改失败");
        }
    }
}
